<!DOCTYPE HTML>
<html>
<head>
<title>Ethiopia Family Medecine Assessment</title>
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.5.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />
<script src="jquery-1.5.min.js"></script>
<script src="ethiopia.js"></script>
<script src="persistence.js" type="application/javascript"></script>
<script src="persistence.store.sql.js" type="application/javascript"></script>
<script src="persistence.store.websql.js" type="application/javascript"></script>
<script src="jquery.mobile-1.0a4.min.js"></script>
<link rel="stylesheet" href="ethiopia.css" />
</head>

<body>

<div data-role="page">

	<div data-role="header" data-theme="b">
		<h1>Settings</h1>
		<a href="index.html" class='ui-btn-left ui-btn-back' data-icon='arrow-l' rel="external">Back</a>
	</div><!-- /header -->

	<div data-role="content" data-theme="b">
		<div>Device identity: <input name="device-identity" id="device-identity" type="text"></input></div>
		<div>Enter password: <input name="password-drop" id="password-drop" type="password"></input></div>
		<div data-role="button" id="update-device-identity" >Update device identity</div>
		<div data-role="button" id="drop-websql-db" >Drop WebSQL database</div>
		<div><br></br></div>
		<!-- <div data-role="button" id="add-websql-sample" >DEV ONLY:Add sample data to the WebSQL database</div> -->
		<div data-role="button" id="init-propforlists" >Add default lists</div>
		<div data-role="button" id="dump-websql-db" >Save websql DB to JSON file</div>
		<div data-role="button" id="run-sql" >Run SQL commands</div>
		<div data-role="fieldcontain">
			<textarea cols="35" rows="8" name="sql-textarea" id="sql-textarea"></textarea>
		</div>
		<div id="sql-results" name="sql-results" style="color:#900;"></div>
		
	</div>

</div><!-- /page -->

<script>
initApp(handleBack);
window.onload = doOnLoad;

function doOnLoad() {
	document.getElementsByName("device-identity")[0].value = getDeviceID();
}

function handleBack(){
	if (typeof device  != "undefined"){
		document.addEventListener("backbutton", function(){goToPage("index.html");}, false);
	}
}

$("#update-device-identity").bind("click",(function () {
	if( confirm("Are you sure you want to update the device identity ?") ){
		if (document.getElementsByName("password-drop")[0].value == "fma" ) {
			setDeviceID(document.getElementsByName("device-identity")[0].value);
			alert("Updated device identity");
		}
		else {
			alert("Password incorrect");
		}
  	}
  })
);

$("#drop-websql-db").bind("click",(function () {
	if( confirm("Are you sure you want to drop the WebSQL Database ?") ){
		if (document.getElementsByName("password-drop")[0].value == "fma" ) {
			dropWebSQLDB(function(){			
				alert("Db dropped Done")
				showDefaultMessage();
				stall(500);		// on device need to wait until db action completes
				window.location.href = "index.html"; 
			});
		}
		else {
			alert("Password incorrect");
		}
  	}
  })
);

$("#add-websql-sample").bind("click",(function () {
	if( confirm("Are you sure you want to Add some WebSQL data to the Database ?") ){
		addWebSQLDataSample(function(){
			alert("Samples added");
			});
  	}
  })
);


$("#init-propforlists").bind("click",(function () {
	if( confirm("Are you sure you want to add default lists ?") ){
		initDefaultPropForLists(function(){
			alert("Default lists added");
				showDefaultMessage();
				stall(500);		// on device need to wait until db action completes
				window.location.href = "index.html"; 
		});
  	}
  })
);


$("#dump-websql-db").bind("click",(function () {
	if( confirm("Are you sure you want to save database to file, this may take time ?") ){
		persistence.dump( function(dump) {
			console.log(dump);
			ExportDB(dump, function(){
				alert("Created JSON dump file");
					showDefaultMessage();
					stall(500);		// on device need to wait until db action completes
					window.location.href = "index.html";
			});					
		});
  	}
  })
);

$("#run-sql").bind("click",(function () {
	if( confirm("Are you sure you want to run sql commands ?") ){
		if (document.getElementsByName("password-drop")[0].value == "fma" ) {
			RunSQL(document.getElementsByName("sql-textarea")[0].value, 
				function(errors,err, sql){			
	//				alert("Command Completed")
	//				showDefaultMessage();
			 		var strErrors = "";
					if (err.code > 1) { 
						strErrors = "SQL Error [" + err.code + "]: " + err.message + "\n\nCommand: "+ sql + "\n";
						alert( strErrors );
						
						document.getElementsByName("sql-results")[0].innerHTML = strErrors;
					}
				},
				function(errors,err, sql){			
					alert("Command Completed")
				});
		}
		else {
			alert("Password incorrect");
		}
  	}
  })
);
function RunSQL(sql, callback1, callback2) {
	var splitSQL = sql.split("\n");
	var queries = [];
	var errors = 0;

	for (var row = 0; row < splitSQL.length; row++)	{
		queries[row] = [splitSQL[row], null];
	}
	
  	persistence.transaction(function(tx){
		executeQueriesSeqReportErrors (tx, queries, callback1, callback2); 	
  	});
/*
  	persistence.transaction(function(tx){
	  for (var command = 0; command < splitSQL.length; command++) {
	  	query = splitSQL[command];
	    tx.executeSql(
	    	query, 
	    	null, 
	    	function(results){
		        var nRows = 0;
		        results.forEach(function(result) {
		        	nRows++;
		          });
		      	// alert( "SQL command:\n\n"+splitSQL[command]+ "\n\nresult: " + nRows + " rows.");
		      	console.log(results);
		    },
			function(_, err) {
	            console.log(err.message);
	            callback(_, err);
	        });
	  }
	});
*/

}

  /**
   * Utility function to execute a series of queries in an asynchronous way
   * @param tx the transaction to execute the queries on
   * @param queries an array of [query, args] tuples
   * @param callback1 the function to call after each query executed
   * @param callback2 the function to call when all queries have been executed
   */
  function executeQueriesSeqReportErrors (tx, queries, callback1, callback2) {
    queries.reverse();			// otherwise goes last to first
    var callbackArgs = [];
    for ( var i = 3; i < arguments.length; i++) {
      callbackArgs.push(arguments[i]);
    }
    persistence.asyncForEach(queries, function(queryTuple, callback1) {
        tx.executeSql(queryTuple[0], queryTuple[1], null, function(_, err) {
            console.log(err.message);
            // Should be done in highest level callback
			if (err.code > 0) { 
//				strErrors = "SQL Error [" + err.code + "]: " + err.message + "\n\n"
//				alert( strErrors + "Command: "+ queryTuple[0] + "\n" );			

				strErrors = "SQL Error [" + err.code + "]: " + err.message + "<br>Command: "+ queryTuple[0] + "<br><br>";
//				alert( strErrors );
				
	            document.getElementsByName("sql-results")[0].innerHTML += strErrors;
			}
            callback1(_, err);
          });
      }, function(result, err) {
        if (err && callback2) {
          callback2(result, err);
          return;
        }
        if(callback2) callback2.apply(null, callbackArgs);
      });
  }
  
function ExportDB(objArray, callback)
{
	/* Object structure: Object -> many single dimension arrays. 
	Each array can have multiple elements, each with the structure: "elementname: value"
	*/
	var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
	
	var str = JSON.stringify(array);
	
	var clean = true;
	var now = new Date();
	var nowStr = formatDate(now) + "_" + formatTime(now, clean);
	var dumpFileName = nowStr + "." + "txt";

	if (typeof navigator.fileMgr != "undefined") {
		navigator.fileMgr.writeAsText(appPath+"/"+dumpFileName, str, true, null, fail);
	} else {
		console.log(str);
		// alert(str);
	}	
	if (callback) callback();
}

</script>
</body>
</html>